package com.leo.erp.web.functions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leo.erp.dto.FunctionsExecution;
import com.leo.erp.dto.UserBusinessExecution;
import com.leo.erp.entity.Functions;
import com.leo.erp.entity.User;
import com.leo.erp.enums.FunctionsStateEnum;
import com.leo.erp.enums.UserBusinessStateEnum;
import com.leo.erp.service.FunctionsService;
import com.leo.erp.service.UserBusinessService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.HttpServletRequestUtil;

@Controller
@RequestMapping(value = "/functions")
public class FunctionsManagementController {
	@Autowired
	private FunctionsService functionsService;
	@Autowired
	private UserBusinessService userBusinessService;
	
	@RequestMapping(value = "/findByIds")
	@ResponseBody
	public Map<String, Object> findByIds(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String functionsIds = HttpServletRequestUtil.getString(request, "functionsIds");
		JSONObject outer = new JSONObject();
		
		//存放数据json数组
		JSONArray dataArray = new JSONArray();
		FunctionsExecution fe = functionsService.findByIds(functionsIds);
		if(fe.getState() == FunctionsStateEnum.SUCCESS.getState()) {
			outer.put("total", fe.getFunctionsList().size());
            for(Functions functions : fe.getFunctionsList()) {
            	JSONObject item = new JSONObject();
                item.put("Id", functions.getFunctionsId());
                item.put("Name", functions.getName());
                item.put("PushBtn", functions.getPushBtn());
                item.put("op", 1);
                dataArray.add(item);
            }
            outer.put("rows", dataArray);
            modelMap.put("data", outer);
            modelMap.put("success", true);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "获取数据失败");
		}
		
		return modelMap;
	}
	
	/**
     * 角色对应功能显示
     * @param request
     * @return
     */
	@RequestMapping(value = "/findRoleFunctions")
	@ResponseBody
	public JSONArray findRoleFunctions(HttpServletRequest request){
		//获取前台传过来的值
		String type = HttpServletRequestUtil.getString(request, "UBType");
		String keyId = HttpServletRequestUtil.getString(request, "UBKeyId");
		
		JSONArray arr = new JSONArray();
		FunctionsExecution fe = functionsService.findRoleFunctions("0");
		//开始拼接json数据
		JSONObject outer = new JSONObject();
		outer.put("id", 1);
        outer.put("text", "功能列表");
        outer.put("state", "open");
        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        
        if(null != fe.getFunctionsList()) {
        	//根据条件从列表里面移除"系统管理"
        	List<Functions> dataList = new ArrayList<>();
        	for(Functions fun : fe.getFunctionsList()) {
        		//从session中获取租户id
                String loginName = null;
                Object userInfo = request.getSession().getAttribute("user");
                if(userInfo != null) {
                    User user = (User) userInfo;
                    loginName = user.getLoginName();
                }
                if(("admin").equals(loginName)) {
                    dataList.add(fun);
                } else {
                    if(!("系统管理").equals(fun.getName())) {
                        dataList.add(fun);
                    }
                }
        	}
        	dataArray = getFunctionList(dataList, type, keyId);
            outer.put("children", dataArray);
        }
        arr.add(outer);
		return arr;
	}
	
	private JSONArray getFunctionList(List<Functions> dataList, String type, String keyId) {
		JSONArray dataArray = new JSONArray();
        if (null != dataList) {
            for (Functions functions : dataList) {
                JSONObject item = new JSONObject();
                item.put("id", functions.getFunctionsId());
                item.put("text", functions.getName());
                //Boolean flag = false;
                UserBusinessExecution ue = new UserBusinessExecution();
                try {
                    ue = userBusinessService.checkIsUserBusinessExist(type, keyId, "[" + functions.getFunctionsId() + "]");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (ue.getState() == UserBusinessStateEnum.SUCCESS.getState()) {
                    item.put("checked", true);
                }
                FunctionsExecution fe = functionsService.findRoleFunctions(functions.getNumber());
                if(fe.getState() == FunctionsStateEnum.SUCCESS.getState()) {
                    JSONArray funArr = getFunctionList(fe.getFunctionsList(), type, keyId);
                    item.put("children", funArr);
                    dataArray.add(item);
                } else {
                    dataArray.add(item);
                }
            }
        }
        return dataArray;
	}

	@RequestMapping(value = "/checkIsNameExist")
	@ResponseBody
	public Map<String, Object> checkIsNameExist(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String name = HttpServletRequestUtil.getString(request, "name");
		
		FunctionsExecution fe = functionsService.checkIsNameExist(name);
		if(fe.getState() == FunctionsStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("flag", true);
			modelMap.put("msg", "功能名已经存在");
		}else {
			modelMap.put("success", false);
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/updateFunctions")
	@ResponseBody
	public Map<String, Object> updateFunctions(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String beanJson = HttpServletRequestUtil.getString(request, "info");
		int functionsId = HttpServletRequestUtil.getInt(request, "id");
		Functions functions = JSON.parseObject(beanJson, Functions.class);
		functions.setFunctionsId(functionsId);
		FunctionsExecution fe = functionsService.updateFunctions(functions);
		if(fe.getState() == FunctionsStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("msg", "更改功能信息成功");
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "更改功能信息失败");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/addFunctions")
	@ResponseBody
	public Map<String, Object> addFunctions(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String beanJson = HttpServletRequestUtil.getString(request, "info");
		
		//插入数据
		try {
			Functions functions = JSON.parseObject(beanJson, Functions.class);
			//查询功能名称是否存在
			FunctionsExecution fe1 = functionsService.checkIsNameExist(functions.getName());
			if(fe1.getState() == FunctionsStateEnum.SUCCESS.getState()) {
				modelMap.put("success", false);
				modelMap.put("msg", "功能名已存在");
			}else {
				//插入功能数据
				FunctionsExecution fe = functionsService.insertFunctions(beanJson);
				if(fe.getState() == FunctionsStateEnum.SUCCESS.getState()) {
					modelMap.put("success", true);
				}else {
					modelMap.put("success", false);
					modelMap.put("msg", "插入数据异常");
				}
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/deleteFunctions")
	@ResponseBody
	public Map<String, Object> deleteFunctions(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的id
		int functionsId = HttpServletRequestUtil.getInt(request, "ids");
		
		FunctionsExecution fe = functionsService.deleteFunctions(functionsId);
		if(fe.getState() == FunctionsStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "删除失败");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String name = HttpServletRequestUtil.getString(request, "name");
		String type = HttpServletRequestUtil.getString(request, "type");
		int currentPage = HttpServletRequestUtil.getInt(request, "currentPage");
		int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
		
		FunctionsExecution fe = new FunctionsExecution();
		fe = functionsService.getFunctionsPageList(name, type, currentPage, pageSize);
		if(fe.getState() == FunctionsStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("pages", fe.getPages());//总页数
			modelMap.put("total", fe.getTotal());//总数
			
			Map<String, Object> map = new HashMap<>();
			map.put("rows", fe.getFunctionsPageList());
			map.put("total", fe.getTotal());
			//modelMap.put("logList", le.getLogPageList());
			modelMap.put("functionsList", map);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "查询列表失败");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/getfunctionslist")
	@ResponseBody
	public Map<String, Object> getFunctionsList(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String pNumber = HttpServletRequestUtil.getString(request, "pNumber");
		int enabled = HttpServletRequestUtil.getInt(request, "enabled");
		String deleteFlag = HttpServletRequestUtil.getString(request, "deleteFlag");
		String hasFunctions = HttpServletRequestUtil.getString(request, "hasFunctions");
		
		//存放数据json数组
        JSONArray dataArray = new JSONArray();
		
        //当前用户所拥有的功能列表，格式如：[1][2][5]
        String fc = hasFunctions;
		List<Functions> functionsList = functionsService.getFunctionsList(pNumber, enabled, deleteFlag);
		
		if(functionsList.size() > -1) {
			dataArray = getMenuByFunction(functionsList, fc);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "查询数据失败");
		}
		if(dataArray.size() > -1) {		
			modelMap.put("count", dataArray.size());
			modelMap.put("functionsList", dataArray);
			modelMap.put("success", true);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "查询数据失败");
		}
		
		return modelMap;
	}

	private JSONArray getMenuByFunction(List<Functions> functionsList, String fc) {
		JSONArray dataArray = new JSONArray();
        for (Functions functions : functionsList) {
            JSONObject item = new JSONObject();
            List<Functions> newList = functionsService.getRoleFunctions(functions.getNumber());
            item.put("id", functions.getFunctionsId());
            item.put("text", functions.getName());
            item.put("icon", functions.getIcon());
            if (newList.size() > 0) {
            	 JSONArray childrenArr = getMenuByFunction(newList, fc);
                 if(childrenArr.size()>0) {
                     item.put("children", childrenArr);
                     dataArray.add(item);
                 }
             } else {
                 item.put("url", functions.getUrl());
                 if (fc.indexOf("[" + functions.getFunctionsId() + "]") != -1) {
                     dataArray.add(item);
                 }
             }
        }
        return dataArray;
	}
}
